
from fastapi import FastAPI, HTTPException, Depends, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from database.database import engine, get_db
from models.article import Article
from services.article_generator import ArticleGenerator
from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime
import os

# 创建数据库表
from models.article import Base as ArticleBase
ArticleBase.metadata.create_all(bind=engine)

app = FastAPI(title="头条热门原创图文推送助手", version="1.0.0")

# 挂载静态文件
app.mount("/static", StaticFiles(directory="frontend/static"), name="static")
templates = Jinja2Templates(directory="frontend/templates")

class ArticleCreate(BaseModel):
    title: str
    content: str
    summary: Optional[str] = None
    cover_image: Optional[str] = None
    tags: Optional[List[str]] = None
    scheduled_time: Optional[datetime] = None

class ArticleUpdate(BaseModel):
    title: Optional[str] = None
    content: Optional[str] = None
    summary: Optional[str] = None
    cover_image: Optional[str] = None
    tags: Optional[List[str]] = None
    status: Optional[str] = None
    scheduled_time: Optional[datetime] = None

@app.get("/")
async def dashboard(request: Request):
    return templates.TemplateResponse("dashboard.html", {"request": request})

@app.get("/api/articles")
async def get_articles(
    skip: int = 0,
    limit: int = 50,
    status: Optional[str] = None,
    db: Session = Depends(get_db)
):
    query = db.query(Article)
    if status:
        query = query.filter(Article.status == status)
    
    articles = query.order_by(Article.created_at.desc()).offset(skip).limit(limit).all()
    return articles

@app.get("/api/articles/{article_id}")
async def get_article(article_id: int, db: Session = Depends(get_db)):
    article = db.query(Article).filter(Article.id == article_id).first()
    if not article:
        raise HTTPException(status_code=404, detail="文章未找到")
    return article

@app.post("/api/articles/generate")
async def generate_articles(
    count: int = 3,
    db: Session = Depends(get_db)
):
    generator = ArticleGenerator()
    articles = generator.generate_daily_articles(count)
    article_ids = generator.save_articles_to_db(articles)
    
    return {
        "message": f"成功生成{len(articles)}篇文章",
        "article_ids": article_ids
    }

@app.post("/api/articles")
async def create_article(
    article: ArticleCreate,
    db: Session = Depends(get_db)
):
    db_article = Article(**article.dict())
    db.add(db_article)
    db.commit()
    db.refresh(db_article)
    return db_article

@app.put("/api/articles/{article_id}")
async def update_article(
    article_id: int,
    article: ArticleUpdate,
    db: Session = Depends(get_db)
):
    db_article = db.query(Article).filter(Article.id == article_id).first()
    if not db_article:
        raise HTTPException(status_code=404, detail="文章未找到")
    
    update_data = article.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_article, field, value)
    
    db.commit()
    db.refresh(db_article)
    return db_article

@app.delete("/api/articles/{article_id}")
async def delete_article(article_id: int, db: Session = Depends(get_db)):
    db_article = db.query(Article).filter(Article.id == article_id).first()
    if not db_article:
        raise HTTPException(status_code=404, detail="文章未找到")
    
    db.delete(db_article)
    db.commit()
    return {"message": "文章已删除"}

@app.post("/api/articles/{article_id}/publish")
async def publish_article(article_id: int, db: Session = Depends(get_db)):
    article = db.query(Article).filter(Article.id == article_id).first()
    if not article:
        raise HTTPException(status_code=404, detail="文章未找到")
    
    article.status = "published"
    article.scheduled_time = datetime.now()
    db.commit()
    
    return {"message": "文章已发布", "article_id": article_id}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
